package com.books.servlet;

import com.books.bean.User;
import com.books.service.UserService;
import com.books.service.impl.UserServiceImpl;
import com.books.utils.Constant;
import com.books.utils.RequestParameterUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 用户的servlet
 * 作用：接收请求---》通过Service处理请求
 * 响应请求
 */

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    //声明UserService对象
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * 统一处理浏览器的http://localhost:8080/userServlet的请求
     *
     * @param request 封装请求相关信息的对象
     * @return response 封装响应相关信息的对象
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置POST请求中数据的解码方式
//        request.setCharacterEncoding("UTF-8");
        String type = request.getParameter(Constant.REQUEST_PARAMETER_TYPE);
        if (type != null && !"".equals(type)) {
            if (Constant.SERVLET_TYPE_SAVE.equals(type)) {
                //添加用户信息
                try {
                    saveOrUpdateUser(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (Constant.SERVLET_TYPE_UPDATE.equals(type)) {
                //更新用户信息

            } else if (Constant.SERVLET_TYPE_DELETE.equals(type)) {
                //删除用户信息
                deleteUserById(request, response);
            } else if (Constant.SERVLET_TYPE_QUERY.equals(type)) {
                //查询用户
                queryUser(request, response);
            } else if (Constant.SERVLET_TYPE_QUERYBYID.equals(type)) {
                //根据id查询单条记录
                String id = request.getParameter("id");
                User user = userService.queryById(Integer.parseInt(id));
                //跳转到更新的页面同时保存数据到Request作用域中
                request.setAttribute("user", user);
                request.getRequestDispatcher(response.encodeRedirectURL("user/userUpdate.jsp")).forward(request, response);
            } else if (Constant.SERVLET_TYPE_CHECK.equals(type)) {
                //验证账号是否存在
                String userName = request.getParameter("userName");
                String s = userService.checkUserName(userName);
                response.getWriter().println(s);
                response.flushBuffer();
            }
        } else {
            //查询用户信息
            queryUser(request, response);
        }


    }

    /**
     * @param null
     * @return null
     * 根据id删除用户信息
     */

    private void deleteUserById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取需要删除的用户编号
        String id = request.getParameter("id");
        //通过service处理删除操作
        Integer count = userService.deleteById(Integer.parseInt(id));//强制类型转换
        //然后做一个重定向查询用户信息的操作
        response.sendRedirect(request.getContextPath() + "/userServlet");
    }

    /**
     * 添加用户的方法
     *
     * @param request
     * @param response
     * @throws Exception
     */
    private void saveOrUpdateUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.获取用户表单提交的信息
//        User user = new User();
//        user.setUserName(request.getParameter("userName"));
//        user.setPassword(request.getParameter("password"));
//        user.setPhoneNum(request.getParameter("phoneNum"));
//        user.setEmail(request.getParameter("email"));
        User user = RequestParameterUtils.getRequestParameterForReflect(request, User.class);
        Integer count = -1;
        if (user.getId() != null && user.getId() > 0) {
            //表示更新
            count = userService.updateUser(user);


        } else {
            //count就是影响的行数
            count = userService.addUser(user);
        }

        if (count > 0) {
            //表示插入成功 再做一次查询操作
            response.sendRedirect(request.getContextPath() + "/userServlet");

        } else {
            //表示插入失败
            System.out.println("插入失败...");

            //TODO跳转到失败页面
        }
    }

    /**
     * @param null
     * @return null
     * <p>
     * 查询用户信息
     */

    private void queryUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通过service查询所有的用户信息
        List<User> list = userService.getUser(null);
        //把查询的信息绑定在作用域中
        request.setAttribute("list", list);
        //页面跳转到user.jsp中
        request.getRequestDispatcher("/user/user.jsp").forward(request, response);
    }

}
